package org.tao.lightningmq.nameserver.handler;

import com.alibaba.fastjson2.JSON;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tao.lightningmq.common.enums.NameServerEventCode;
import org.tao.lightningmq.common.enums.NameServerResponseCode;
import org.tao.lightningmq.common.event.EventBus;
import org.tao.lightningmq.common.event.model.BaseEvent;
import org.tao.lightningmq.common.tcp.TcpMsg;
import org.tao.lightningmq.nameserver.event.model.ReplicationMsgEvent;

/**
 * @Author lht
 * @date 2025/1/17 - 14:33
 * @description:
 */
@ChannelHandler.Sharable
public class SlaveReplicationServerHandler extends SimpleChannelInboundHandler<TcpMsg> {

    private static final Logger LOGGER = LoggerFactory.getLogger(SlaveReplicationServerHandler.class);

    private EventBus eventBus;

    public SlaveReplicationServerHandler(EventBus eventBus) {
        this.eventBus = eventBus;
        eventBus.init();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TcpMsg tcpMsg) throws Exception {
        int code = tcpMsg.getCode();
        LOGGER.info("code is {}", code);
        byte[] body = tcpMsg.getBody();
        BaseEvent event = null;
        if (NameServerEventCode.MASTER_REPLICATION_MSG.getCode() == code) {
            event = JSON.parseObject(body, ReplicationMsgEvent.class);
            event.setContext(channelHandlerContext);
            eventBus.publish(event);
        } else if (NameServerResponseCode.MASTER_START_REPLICATION_ACK.getCode() == code) {
            LOGGER.info("成功注册到主节点!");
        } else if(NameServerResponseCode.HEART_BEAT_SUCCESS.getCode() == code){
            // 心跳信息ACK
        }
    }
}
